import {Injectable} from '@nestjs/common';
import {Category} from './category.entity'
import {InjectRepository} from "@nestjs/typeorm";
import {Repository} from "typeorm";
import {pagination} from "../../utils/pagination";
import {Bookmark} from "../bookmark.entity";
const {
    categoryNameExpire,
    categoryIDExpire,
    categoryErrExpire,
    categoryDelBookmarkExpire
} = require('../../provider/error')

@Injectable()
export class CategoryService {
    constructor(@InjectRepository(Category) private category: Repository<Category>,
                @InjectRepository(Bookmark) private bookmark: Repository<Bookmark>) {
    }

    async categoryList(params) {
        const res = await pagination(params, this.category, 'category')
        return res
    }

    createCategory(bodyData) {
      if (!bodyData || !bodyData.name || bodyData.name == '' ||
          !bodyData.icon || bodyData.icon == '') return categoryNameExpire()
        this.category.save({
            name: bodyData.name,
            icon: bodyData.icon,
            sort: bodyData.sort ? bodyData.sort : 1,
            create_time: new Date(),
            updated_time: new Date()
        })
        return []
    }

    async updatedCategory(bodyData) {
        if (!bodyData.id) return categoryIDExpire()
        if (!bodyData || !bodyData.name || bodyData.name == '' ||
            !bodyData.icon || bodyData.icon == '') return categoryNameExpire()
        const res = await this.category.update(bodyData.id, {
            name: bodyData.name,
            icon: bodyData.icon,
            sort: bodyData.sort ? bodyData.sort : 1,
            updated_time: new Date()
        })
        if (res.affected !== 1) return categoryErrExpire()
        return []
    }

    async delCategory(params) {
        const findRes = await this.bookmark.findOne({where: {category_id: params.id}})
        if (findRes) return categoryDelBookmarkExpire()
        if (!params.id) return categoryIDExpire()
        const res = await this.category.delete(params.id)
        if (res.affected !== 1) return categoryErrExpire()
        return []
    }

    async categorySelect(){
        const res =await this.category.createQueryBuilder("category").addOrderBy('sort', 'DESC').getMany()
        const data = {}
        res.forEach(t => {
          data[t.id] =  t.name
        })
        return data
    }
}
